package day05.pm;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * 键盘事件 小球运动
 */
public class Demo07 {
    public static void main(String[] args) {
        JFrame f  = new JFrame("小球运动");
        f.setSize(300,400);
        f.setResizable(false);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        MyBall mb = new MyBall();
        f.add(mb);
        f.addKeyListener(mb);
        mb.addKeyListener(mb);
        f.setVisible(true);
    }
}

class MyBall extends JPanel implements KeyListener {
    int x=30;
    int y=30;
    @Override
    public void paint(Graphics g) {
        g.clearRect(0,0,300,400);
        g.fillOval(x,y,20,20);
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
        int code = e.getKeyCode();
        if(code==37){//左键
            x--;
            if(x<=0){
                x=0;
            }
        }
        if(code==38){
            y--;
        }
        if(code==39){
            x++;
            if(x>=270){
                x=270;
            }
        }
        if(code==40){
            y++;
        }
        repaint();
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }
}
